import { createRouter, createWebHistory } from 'vue-router'
// import HomeView from '@/views/homePage.vue'
import { useUserState, type typeUserInfo } from '@/store/userState'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home/0'
    },
    {
      path: '/user',
      redirect: '/user/home'
    },
    {
      path: '/home/:typeid',
      name: 'home',
      component: () => import('@/views/homePage.vue')
    },
    {
      path: '/play/:vod_id',
      name: 'play',
      component: () => import('@/views/playerPage.vue')
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('@/views/searchPage.vue')
    },
    {
      path: '/user',
      name: 'user',
      component: () => import('@/views/userPage.vue'),
      children: [
        {
          path: 'home',
          name: 'userHome',
          component: () => import('@/views/userPage_home.vue')
        },
        {
          path: 'histry',
          name: 'userHistry',
          component: () => import('@/views/userPage_histry.vue')
        },
        {
          path: 'collect',
          name: 'collect',
          component: () => import('@/views/userPage_collect.vue')
        }
      ]
    },
    {
      path: '/403',
      name: '403',
      component: () => import('@/views/403.vue')
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/404.vue')
    },
    {
      path: '/:pathMatch(.*)',
      redirect: '/'
    }
  ]
})

router.beforeEach(async to => {
  if (to.matched[0]['name'] == 'user') {
    let pass = false
    try {
      const userState = useUserState()
      const userInfo = await userState.getUserInfo()
      if (userInfo) pass = true
    } catch (error) {
      pass = false
    }
    if (!pass) {
      return '/403'
    }
  }
})

export default router
